package org.daochong.fastdev.funcs;

import java.sql.SQLException;

import org.daochong.fastdev.Context;
import org.daochong.fastdev.Function;
import org.daochong.fastdev.OperationId;
import org.daochong.fastdev.util.FastDevUtils;
import org.daochong.lang.BeanUtil;
import org.daochong.lang.StringUtils;

public class CreateFunction implements Function {

	public boolean is(String id) {
		return FastDevUtils.operEntity("create", id);
	}

	public void exec(String key, String prop, Context context) throws SQLException {
		if (!is(key))
			throw new RuntimeException("Function  not match [" + key + "]");
		prop = BeanUtil.formatString(prop, context);
		if ("create".equals(key)) {
			create(prop, context);
		} else {
			createEntity(key.substring(7), prop, context);
		}
	}

	private void create(String prop, Context context) throws SQLException {
		if (StringUtils.isEmpty(prop))
			return;
		for (OperationId oid : FastDevUtils.operationIds(prop)) {
			Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
			Object obj = context.getJpaOperations().create(entity,
					BeanUtil.getExtDatas(entity, context.getParameters()));
			context.add(oid, obj);
		}
	}

	private void createEntity(String entityType, String prop, Context context) throws SQLException {
		OperationId oid = FastDevUtils.operationId(entityType);
		Object entity = context.getClassMappingFactory().getEntity(oid.getId(), context.getParameters());
		Object obj = null;
		if (!StringUtils.isEmpty(prop)) {
			obj = context.getJpaOperations().createBySql(prop, context.getParameters());
		} else {
			obj = context.getJpaOperations().create(entity, BeanUtil.getExtDatas(entity, context.getParameters()));
		}
		context.add(oid, obj);
	}

}
